<template>
  <v-container fluid>
    <v-row>
      <v-col cols="12" md="8" lg="6">
        <v-card elevation="2">
          
          <v-card-text>
            <v-form ref="settingsForm" v-model="formValid" @submit.prevent="saveSettings">
              <!-- 入园时间 -->
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="settings.arrival_time"
                    label="入园时间"
                    prepend-icon="mdi-login"
                    type="time"
                    variant="outlined"
                    :rules="timeRules"
                    hint="超过此时间未入园将标记为异常"
                    persistent-hint
                    class="mb-3"
                  ></v-text-field>
                </v-col>
              </v-row>
              
              <!-- 离园时间 -->
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="settings.departure_time"
                    label="离园时间"
                    prepend-icon="mdi-logout"
                    type="time"
                    variant="outlined"
                    :rules="timeRules"
                    hint="正常离园时间"
                    persistent-hint
                    class="mb-3"
                  ></v-text-field>
                </v-col>
              </v-row>
              
              <!-- 限制标记时间 -->
              <v-row>
                <v-col cols="12">
                  <v-text-field
                    v-model="settings.modification_limit_time"
                    label="限制标记时间"
                    prepend-icon="mdi-lock-clock"
                    type="time"
                    variant="outlined"
                    :rules="timeRules"
                    hint="超过此时间教师不能修改离园状态"
                    persistent-hint
                    class="mb-4"
                  ></v-text-field>
                </v-col>
              </v-row>
              
              <!-- 操作按钮 -->
              <v-row>
                <v-col cols="12" class="d-flex gap-3">
                  <v-btn
                    type="submit"
                    color="primary"
                    prepend-icon="mdi-content-save"
                    :loading="saving"
                    :disabled="!formValid || !hasChanges"
                    size="large"
                  >
                    保存设置
                  </v-btn>
                  
                  <v-btn
                    color="grey"
                    prepend-icon="mdi-refresh"
                    @click="resetSettings"
                    :disabled="saving"
                    variant="outlined"
                    size="large"
                  >
                    重置
                  </v-btn>
                </v-col>
              </v-row>
              
              <!-- 考勤记录管理 -->
              <v-divider class="my-6"></v-divider>
              
              <v-row>
                <v-col cols="12">
                  <h3 class="text-h6 mb-4">考勤记录管理</h3>
                  <v-alert
                    type="info"
                    variant="tonal"
                    class="mb-4"
                  >
                    为所有学生生成当日考勤记录，初始状态为"未入校"。如果当日已有记录则无法重复生成。
                  </v-alert>
                  
                  <v-btn
                    color="success"
                    prepend-icon="mdi-plus-circle"
                    @click="generateDailyRecords"
                    :loading="generating"
                    size="large"
                    variant="elevated"
                  >
                    生成当日考勤记录
                  </v-btn>
                </v-col>
              </v-row>
            </v-form>
          </v-card-text>
        </v-card>
      </v-col>
      
      <!-- 设置说明 -->
    </v-row>
  </v-container>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(true)
const saving = ref(false)
const generating = ref(false)
const formValid = ref(false)
const settingsForm = ref(null)

// 设置数据
const settings = ref({
  arrival_time: '08:45',
  departure_time: '17:30',
  modification_limit_time: '14:00'
})

const originalSettings = ref({
  arrival_time: '08:45',
  departure_time: '17:30',
  modification_limit_time: '14:00'
})

// 表单验证规则
const timeRules = [
  v => !!v || '时间不能为空',
  v => /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(v) || '请输入正确的时间格式 (HH:MM)'
]

// 计算属性
const hasChanges = computed(() => {
  return settings.value.arrival_time !== originalSettings.value.arrival_time ||
         settings.value.departure_time !== originalSettings.value.departure_time ||
         settings.value.modification_limit_time !== originalSettings.value.modification_limit_time
})

// 方法
const loadSettings = async () => {
  try {
    loading.value = true
    const response = await api.get('/settings/attendance')
    
    if (response.data.success) {
      const data = response.data.data
      
      // 转换时间格式 (从 HH:MM:SS 到 HH:MM)
      settings.value = {
        arrival_time: data.arrival_time?.value?.substring(0, 5) || '08:45',
        departure_time: data.departure_time?.value?.substring(0, 5) || '17:30',
        modification_limit_time: data.modification_limit_time?.value?.substring(0, 5) || '14:00'
      }
      
      // 保存原始设置
      originalSettings.value = { ...settings.value }
    }
  } catch (error) {
    console.error('加载考勤设置失败:', error)
    window.showNotification?.('加载考勤设置失败', 'error')
  } finally {
    loading.value = false
  }
}

const saveSettings = async () => {
  if (!formValid.value) return
  
  try {
    saving.value = true
    
    // 转换时间格式 (从 HH:MM 到 HH:MM:SS)
    const payload = {
      arrival_time: settings.value.arrival_time + ':00',
      departure_time: settings.value.departure_time + ':00',
      modification_limit_time: settings.value.modification_limit_time + ':00'
    }
    
    const response = await api.put('/settings/attendance', payload)
    
    if (response.data.success) {
      window.showNotification?.(response.data.message, 'success')
      originalSettings.value = { ...settings.value }
    } else {
      window.showNotification?.(response.data.message || '保存失败', 'error')
    }
  } catch (error) {
    console.error('保存考勤设置失败:', error)
    window.showNotification?.('保存考勤设置失败', 'error')
  } finally {
    saving.value = false
  }
}

const resetSettings = () => {
  settings.value = { ...originalSettings.value }
  settingsForm.value?.resetValidation()
}

const generateDailyRecords = async () => {
  try {
    generating.value = true
    
    const response = await api.post('/settings/generate-daily-records')
    
    if (response.data.success) {
      window.showNotification?.(response.data.message, 'success')
    } else {
      window.showNotification?.(response.data.message || '生成记录失败', 'error')
    }
  } catch (error) {
    console.error('生成考勤记录失败:', error)
    const errorMessage = error.response?.data?.message || '生成考勤记录失败'
    window.showNotification?.(errorMessage, 'error')
  } finally {
    generating.value = false
  }
}

const formatTime = (timeStr) => {
  if (!timeStr) return '--'
  return timeStr.length > 5 ? timeStr.substring(0, 5) : timeStr
}

// 生命周期
onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.v-card {
  border-radius: 12px;
}

.v-list-item {
  padding: 8px 0;
}

.v-chip {
  font-weight: 500;
}

.v-btn{
    margin: 10px;
}
</style>